<?php
/**
 * 列表页
 * ============================================================================
 * 网站地址: http://www.pcfcms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小潘 <1131680521@qq.com>
 * Date: 2019-12-21
 */

namespace app\home\controller;
use think\facade\Db;
use app\home\model\Single;
use app\common\model\Arctype;

class Lists extends Base
{
    // 模型标识
    public $nid = '';
    // 模型ID
    public $channel = '';

    // 栏目列表
    public function index($tid = '')
    {
        $pcfglobal = get_global();
        $param = input('param.');
        // 获取当前栏目ID以及模型ID
        $page_tmp = input('param.page/s', 0);
        if (empty($tid) || !is_numeric($page_tmp)) {
            abort(404,'页面不存在');
        }
        $map = [];
        if (!is_numeric($tid) || strval(intval($tid)) !== strval($tid)) {
            $map[] = ['a.dirname','=',$tid];
        } else {
            $map[] = ['a.id','=',$tid];
        }
        $map[] = ['a.is_del','=',0]; // 回收站功能
        $row = Db::name('arctype')->field('a.id, a.current_channel,a.litpic, b.nid')
            ->alias('a')
            ->join('channel_type b', 'a.current_channel = b.id', 'LEFT')
            ->where($map)
            ->find();
        if (empty($row)) {
            abort(404,'页面不存在');
        }
        $tid = $row['id'];
        $this->nid = $row['nid'];
        $this->channel = intval($row['current_channel']);
        $result = $this->logic($tid); // 模型对应逻辑
        $gzpcf = array('field' => $result);
        $this->gzpcf = array_merge($this->gzpcf, $gzpcf);
        $this->assign('gzpcf', $this->gzpcf);
        // 模板文件
        $viewfile = !empty($result['templist']) ? str_replace('.'.$this->view_suffix, '',$result['templist']) : 'lists_'.$this->nid;
        return $this->fetch(":{$viewfile}");
    }

    // 模型对应逻辑 $tid 栏目ID
    private function logic($tid = '')
    {
        $Arctypemodel = new Arctype();
        $pcfglobal = get_global();

        $result = array();
        if (empty($tid)) {
            return $result;
        }
        switch ($this->channel) {
            // 单页模型
            case '6': 
            {
                $arctype_info = $Arctypemodel->getInfo($tid);
                if ($arctype_info) {
                    // 读取当前栏目的内容，否则读取每一级第一个子栏目的内容，直到有内容或者最后一级栏目为止。
                    $result_new = $this->readContentFirst($tid);
                    // 阅读权限
                    if ($result_new['arcrank'] == -1) {
                        return '待审核稿件，你没有权限阅读！';
                    }
                    // 外部链接跳转
                    if ($result_new['is_part'] == 1) {
                        header('Location: '.$result_new['typelink']);
                    }
                    // 自定义字段的数据格式处理
                    $result_new = $this->fieldLogic->getChannelFieldList($result_new, $this->channel);
                    $result = array_merge($arctype_info, $result_new);
                    $result['templist'] = !empty($arctype_info['templist']) ? $arctype_info['templist'] : 'lists_'. $arctype_info['nid'];
                    $result['dirpath'] = $arctype_info['dirpath'];
                    $result['typeid'] = $arctype_info['typeid'];
                }
                break;
            }
            default:
            {
                $result = $Arctypemodel->getInfo($tid);
                break;
            }
        }
        if (!empty($result)) {
            // 自定义字段的数据格式处理
            $result = $this->fieldLogic->getTableFieldList($result, $pcfglobal['arctype_channel_id']);
        }
        // 是否有子栏目，用于标记【全部】选中状态
        $result['has_children'] = $Arctypemodel->hasChildren($tid);
        // seo
        $result['seo_title'] = set_typeseotitle($result['typename'], $result['seo_title']);
        // 获取当前页面URL
        $result['pageurl'] = $this->request->url(true);
        // 给没有type前缀的字段新增一个带前缀的字段，并赋予相同的值
        foreach ($result as $key => $val) {
            if (!preg_match('/^type/i',$key)) {
                $key_new = 'type'.$key;
                !array_key_exists($key_new, $result) && $result[$key_new] = $val;
            }
        }
        return $result;
    }

    /**
     * 读取指定栏目ID下有内容的栏目信息，只读取每一级的第一个栏目
     * @param intval $typeid 栏目ID
     */
    private function readContentFirst($typeid)
    {
        $result = false;
        while (true)
        {
            $singleModel = new Single();
            $result = $singleModel->getInfoByTypeid($typeid);
            if (empty($result['content']) && 'lists_single.html' == strtolower($result['templist'])) {
                $map = array(
                    'parent_id' => $result['typeid'],
                    'current_channel' => 6,
                    'is_hidden' => 0,
                    'status'    => 1,
                );
                $row = Db::name('arctype')->where($map)->field('*')->order('sort_order asc')->find(); // 查找下一级的单页模型栏目
                if (empty($row)) { // 不存在并返回当前栏目信息
                    break;
                } elseif (6 == $row['current_channel']) { // 存在且是单页模型，则进行继续往下查找，直到有内容为止
                    $typeid = $row['id'];
                }
            } else {
                break;
            }
        }
        return $result;
    }

}